<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Redis;
class User extends Model
{

    public static function getInstance()
    {
        static $static = null;
        if (is_null($static)) {
            $static = new self();
        }
        return $static;
    }

    protected $table = 'users';

    //关联user_info表
    public function userInfo()
    {
        return $this->hasOne('App\Model\UserInfo');
    }

    /**
     * @return mixed
     */
    public function getAllUserInfo()
    {
        $data = User::orderBy('id', 'desc')->paginate(2);
        foreach ($data as $key => &$value) {
            $value->descr  = $value->userInfo->descr;
            $value->mobile = $value->userInfo->mobile;
            $value->sex    = $value->userInfo->sex;
            unset($value->userInfo);
        }
        return $data;
    }

    /**
     * @param $user_id
     * @return mixed
     */
    public function getUserInfo($user_id){
        $key = sprintf(RedisKey::$user_info,$user_id);
        $row = Redis::get($key);
        if(!empty($row)) return jsonToArr($row);
        $data = User::where('id',$user_id)->first();
        $data['mobile'] = $data->userInfo->mobile;
        $data['sex'] = $data->userInfo->sex;
        $data['descr'] = $data->userInfo->descr;
        unset($data->userInfo);
        Redis::setex($key,RedisKey::REDIS_COMMON_EXPIRE,objToJson($data));
        return jsonToArr($data);
    }

}
